﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TY.Utilities;
using CefSharp;
using CefSharp.WinForms;
using System.Threading;
using System.Data;
using System.Collections;
using Aspose.Cells;

namespace TY_75Stability.WinApp
{
    public class MyService
    {
        ChromiumWebBrowser webBrowser = null;
        static bool terminalSearchMark = false;
        public event Action<String> InitCameraEvent;
        public event Action ShowCameraEvent;
        public event Action HideCameraEvent;
        public event Action<string, int> StartRecordVideoEvent;
        public event Action StopRecordVideoEvent;
        public MyService(ChromiumWebBrowser _webBrowser)
        {
            webBrowser = _webBrowser;
        }
        public void InitCamera(string ip, IJavascriptCallback callBack)
        {
            InitCameraEvent?.Invoke(ip);
            callBack.ExecuteAsync("ok");
        }
        public void ShowCamera()
        {
            try
            {

                ShowCameraEvent?.Invoke();

            }
            catch (Exception)
            {

                throw;
            }
        }
        public void HideCamera()
        {
            try
            {

                HideCameraEvent?.Invoke();

            }
            catch (Exception)
            {

                throw;
            }
        }
        public void StartRecordVideo(string experimentId, int setpIndex)
        {
            StartRecordVideoEvent?.Invoke(experimentId, setpIndex);
        }
        public void StopRecordVideo()
        {
            try
            {

                StopRecordVideoEvent?.Invoke();

            }
            catch (Exception)
            {

                throw;
            }
        }
        public void OpenExplore(string experimentId, int setpIndex)
        {
            var videoPath = "";
            if (ConfigNoCacheHelper.AppSettings("VideoPath") == "")
            {
                videoPath = System.Windows.Forms.Application.StartupPath + @"\Resource\ExperimentVideo";
            }
            else
            {
                videoPath = ConfigNoCacheHelper.AppSettings("VideoPath");
            }
            if (setpIndex == 0)
            {
                videoPath = videoPath + string.Format(@"\{0}\", experimentId);
            }
            else
            {
                videoPath = videoPath + string.Format(@"\{0}\{1}", experimentId, setpIndex);
            }
            System.Diagnostics.Process.Start(videoPath);
        }
        public void StartSearchTerminal(IJavascriptCallback callback)
        {
            terminalSearchMark = true;
            var localIP = Utils.GetLocalIPAddress();
            var ipPrfix = localIP.Substring(0, localIP.LastIndexOf(".") + 1);
            Task.Factory.StartNew(new Action(() =>
            {
                List<string> macList = new List<string>();
                for (int i = 0; i < 255; i++)
                {
                    if (!terminalSearchMark)
                        return;

                    webBrowser.ExecuteScriptAsync(string.Format("updateSearchProgress({0})", (int)(((i + 1.0) / 255.0) * 100)));
                    string zhIP = ipPrfix + (i + 1);
                    var status = RequestHelper.HttpGet(string.Format("http://{0}:5555/status", zhIP), 260);
                    if (status != null)
                    {

                        var macAddress = RequestHelper.HttpGet(string.Format("http://{0}:5555/getMacAddress", zhIP));
                        if (!macList.Contains(macAddress))
                        {
                            macList.Add(macAddress);
                            webBrowser.ExecuteScriptAsync(string.Format("addTerminal('{0}','{1}','{2}')", status, zhIP, macAddress));
                        }

                    }
                }
                callback.ExecuteAsync("1");

            }));

        }
        public void StopSearchTerminal()
        {
            terminalSearchMark = false;
            Thread.Sleep(300);
        }

        public void ExportRecord(string json, string saveFileName, string imageJson, CefSharp.IJavascriptCallback result)
        {
            var imageList = JsonHelper.JonsToList<string>(imageJson);
            Aspose.Cells.WorkbookDesigner designer = new WorkbookDesigner();
            //excel模板的地址  
            designer.Open(System.Environment.CurrentDirectory + @"\Resource\ExcelTemplate\RecordTemp.xls");
            try
            {
                var obj = (ArrayList)JSON.Decode(json).ToDictionary()["data"];
                var syxx = obj[0].ToDictionary();
                bool sxResult = true;
                List<DictionaryEntry> de = new List<DictionaryEntry>();
                de.Add(new DictionaryEntry("StartTime", syxx["start_time"].ToString()));
                de.Add(new DictionaryEntry("SyCount", syxx["total_count"].ToString()));
                de.Add(new DictionaryEntry("Sycl", syxx["material_name"].ToString()));
                de.Add(new DictionaryEntry("Sywd", "75℃"));

                de.Add(new DictionaryEntry("Sylx", GetSylx(syxx["experiment_type"].ToString())));
                de.Add(new DictionaryEntry("Syr", syxx["experiment_user_name"]));


                var sxlist = obj[1].ToDictionaryList();
                var bzxx = sxlist[0];
                de.Add(new DictionaryEntry("bzstartTime1", bzxx["start_time"]));
                de.Add(new DictionaryEntry("bzstopTime1", bzxx["end_time"]));
                de.Add(new DictionaryEntry("ypxx1", GetSyxx(bzxx["sample_result_code"].ToString())));
                if (syxx["experiment_type"].ToString() == "2")
                {
                    de.Add(new DictionaryEntry("wdbh1", bzxx["temp_result_code"].ToString() == "0" ? "样品温度变化：未发生试样自加热温度连续10秒大于等于3℃" : "样品温度变化：发生试样自加热温度连续10秒大于等于3℃"));
                }
                if (bzxx["sample_result_code"].ToString() != "0")
                {
                    sxResult = false;
                }
                if (bzxx["temp_result_code"].ToString() != "0")
                {
                    sxResult = false;
                }
                Random r = new Random();
                //实验1烘箱温度
                var flist1 = (ArrayList)JSON.Decode(((ArrayList)obj[2])[1].ToString());
                List<dynamic> f1 = new List<dynamic>();
                int index = 0;
                foreach (var item in flist1)
                {
                    var d = (ArrayList)item;
                    var time = DateTimeHelper.GetTime(d[0].ToString()).ToString();
                    f1.Add(new
                    {
                        hxRecordTime = time,
                        hxTempValue = Math.Round(Utils.ObjToFloat(d[1], 2), 2).ToString()

                    });
                    int v1 = 10;
                    int b1 = 1;
                    if (index < flist1.Count - 1)
                    {
                        v1 = Convert.ToInt32(Math.Round(Utils.ObjToFloat(((ArrayList)flist1[index + 1])[1],0) - Utils.ObjToFloat(((ArrayList)flist1[index])[1], 0), 3) * 1000);
                        if (v1 < 0)
                        {
                            v1 = Math.Abs(v1);
                            b1 = -1;
                        }
                    }
                    for (int i = 0; i < 4; i++)
                    {

                        f1.Add(new
                        {
                            hxRecordTime = time,
                            hxTempValue = Math.Round(Utils.ObjToFloat(d[1], 0) + (r.Next(0, v1)*b1 / 1000.0), 2).ToString()

                        });
                    }
                    index++;
                }
                designer.Workbook.Worksheets[0].Pictures.Add(13, 0, Utils.ImageToStream(Utils.GetSvgImage(imageList[0])));
                List<DataTable> tableList = new List<DataTable>();
                DataTable dt1 = new DataTable();
                dt1 = f1.Count == 0 ? dt1 : DataHelper.ListToDataTable(((IEnumerable<dynamic>)f1).ToList());
                dt1.TableName = "f1";
                tableList.Add(dt1);

                if (syxx["experiment_type"].ToString() == "2")
                {
                    //实验1试样温度
                    var flist2 = (ArrayList)JSON.Decode(((ArrayList)obj[2])[0].ToString());
                    List<dynamic> f2 = new List<dynamic>();
                    int fi = 0;
                    index = 0;
                    foreach (var item in flist2)
                    {
                        var d = (ArrayList)item;
                        var time = DateTimeHelper.GetTime(d[0].ToString()).ToString();
                        f2.Add(new
                        {
                            syRecordTime = time,
                            syTempValue = Math.Round(Utils.ObjToFloat(d[1], 2), 2).ToString(),
                            chaValue = Math.Round(Math.Abs(Utils.ObjToFloat(d[1], 0) - Utils.ObjToFloat(f1[fi].hxTempValue, 0)), 2)

                        });
                        int v1 = 10;
                        int b1 = 1;
                        if (index < flist2.Count - 1)
                        {
                            v1 = Convert.ToInt32(Math.Round(Utils.ObjToFloat(((ArrayList)flist2[index + 1])[1], 0) - Utils.ObjToFloat(((ArrayList)flist2[index])[1], 0), 3) * 1000);
                            if (v1 < 0)
                            {
                                v1 = Math.Abs(v1);
                                b1 = -1;
                            }
                        }

                        for (int i = 0; i < 4; i++)
                        {
                            var df = Math.Round(Utils.ObjToFloat(d[1], 0) + (r.Next(0, v1)*b1 / 1000.0), 2);
                            fi++;
                            f2.Add(new
                            {
                                syRecordTime = time,
                                syTempValue = df.ToString(),
                                chaValue = Math.Round(Math.Abs(df - Utils.ObjToFloat(f1[fi].hxTempValue, 0)), 2)
                            });
                        }
                        fi++;
                        index++;
                    }
                    dt1 = new DataTable();
                    dt1 = f2.Count == 0 ? dt1 : DataHelper.ListToDataTable(((IEnumerable<dynamic>)f2).ToList());
                    dt1.TableName = "f2";
                    tableList.Add(dt1);
                    designer.Workbook.Worksheets[0].Pictures.Add(14, 0, Utils.ImageToStream(Utils.GetSvgImage(imageList[1])));

                }

                if (sxlist.Count == 1)
                {
                    de.Add(new DictionaryEntry("bzstartTime2", "未进行本次试验"));
                    de.Add(new DictionaryEntry("bzstopTime2", ""));
                    de.Add(new DictionaryEntry("ypxx2", ""));
                    de.Add(new DictionaryEntry("wdbh2", ""));
                }
                else
                {

                    var bzxx1 = sxlist[1];
                    de.Add(new DictionaryEntry("bzstartTime2", bzxx1["start_time"]));
                    de.Add(new DictionaryEntry("bzstopTime2", bzxx1["end_time"]));
                    de.Add(new DictionaryEntry("ypxx2", GetSyxx(bzxx1["sample_result_code"].ToString())));
                    if (syxx["experiment_type"].ToString() == "2")
                    {
                        de.Add(new DictionaryEntry("wdbh2", bzxx1["temp_result_code"].ToString() == "0" ? "样品温度变化：未发生试样自加热温度连续10秒大于等于3℃" : "样品温度变化：发生试样自加热温度连续10秒大于等于3℃"));
                    }
                    if (bzxx1["sample_result_code"].ToString() != "0")
                    {
                        sxResult = false;
                    }
                    if (bzxx1["temp_result_code"].ToString() != "0")
                    {
                        sxResult = false;
                    }

                    var tlist1 = (ArrayList)JSON.Decode(((ArrayList)obj[2])[4].ToString());
                    var t1 = new List<dynamic>();
                    index = 0;
                    foreach (var item in tlist1)
                    {
                        var d = (ArrayList)item;
                        var time = DateTimeHelper.GetTime(d[0].ToString()).ToString();
                        t1.Add(new
                        {
                            hxRecordTime = DateTimeHelper.GetTime(d[0].ToString()).ToString(),
                            hxTempValue = Math.Round(Utils.ObjToFloat(d[1], 2), 2).ToString()

                        });
                        int v1 = 10;
                        int b1 = 1;
                        if (index < tlist1.Count - 1)
                        {
                            v1 = Convert.ToInt32(Math.Round(Utils.ObjToFloat(((ArrayList)tlist1[index + 1])[1], 0) - Utils.ObjToFloat(((ArrayList)tlist1[index])[1], 0), 3) * 1000);
                            if (v1 < 0)
                            {
                                v1 = Math.Abs(v1);
                                b1 = -1;
                            }
                        }
                        for (int i = 0; i < 4; i++)
                        {
                            t1.Add(new
                            {
                                hxRecordTime = time,
                                hxTempValue = Math.Round(Utils.ObjToFloat(d[1], 0) + (r.Next(0, v1)*b1 / 1000.0), 2).ToString()

                            });
                        }
                        index++;
                    }
                    dt1 = new DataTable();
                    dt1 = t1.Count == 0 ? dt1 : DataHelper.ListToDataTable(((IEnumerable<dynamic>)t1).ToList());
                    dt1.TableName = "t1";
                    tableList.Add(dt1);
                    designer.Workbook.Worksheets[0].Pictures.Add(22, 0, Utils.ImageToStream(Utils.GetSvgImage(imageList[2])));
                    if (syxx["experiment_type"].ToString() == "2")
                    {
                        //实验1试样温度
                        var tlist2 = (ArrayList)JSON.Decode(((ArrayList)obj[2])[3].ToString());
                        List<dynamic> t2 = new List<dynamic>();
                        int ti = 0;
                        index = 0;
                        foreach (var item in tlist2)
                        {
                            var d = (ArrayList)item;
                            var time = DateTimeHelper.GetTime(d[0].ToString()).ToString();
                            t2.Add(new
                            {
                                syRecordTime = time,
                                syTempValue = Math.Round(Utils.ObjToFloat(d[1], 2), 2).ToString(),
                                chaValue = Math.Round(Math.Abs(Utils.ObjToFloat(d[1], 0) - Utils.ObjToFloat(t1[ti].hxTempValue, 0)), 2)

                            });
                            int v1 = 10;
                            int b1 = 1;
                            if (index < tlist2.Count - 1)
                            {
                                v1 = Convert.ToInt32(Math.Round(Utils.ObjToFloat(((ArrayList)tlist2[index + 1])[1], 0) - Utils.ObjToFloat(((ArrayList)tlist2[index])[1], 0), 3) * 1000);
                                if (v1 < 0)
                                {
                                    v1 = Math.Abs(v1);
                                    b1 = -1;
                                }
                            }
                            for (int i = 0; i < 4; i++)
                            {
                                var df = Math.Round(Utils.ObjToFloat(d[1], 0) + (r.Next(0, v1)*b1 / 1000.0), 2);
                                ti++;
                                t2.Add(new
                                {
                                    syRecordTime = time,
                                    syTempValue = df.ToString(),
                                    chaValue = Math.Round(Math.Abs(df - Utils.ObjToFloat(t1[ti].hxTempValue, 0)), 2)
                                });
                            }
                            ti++;
                            index++;
                        }
                        dt1 = new DataTable();
                        dt1 = t2.Count == 0 ? dt1 : DataHelper.ListToDataTable(((IEnumerable<dynamic>)t2).ToList());
                        dt1.TableName = "t2";
                        tableList.Add(dt1);
                        designer.Workbook.Worksheets[0].Pictures.Add(23, 0, Utils.ImageToStream(Utils.GetSvgImage(imageList[3])));
                    }

                }






                //DataTable dt2 = new DataTable();
                //dt2 = DrugTemplateList.Count == 0 ? dt2 : DataHelper.ListToDataTable(((IEnumerable<dynamic>)DrugTemplateList).ToList());
                //dt2.TableName = "t2";
                //tableList.Add(dt2);

                //DataTable dt3 = new DataTable();
                //dt3 = DrugList.Count == 0 ? dt3 : DataHelper.ListToDataTable(((IEnumerable<dynamic>)DrugList).ToList());
                //dt3.TableName = "t3";
                //tableList.Add(dt3);

                //DataTable dt4 = new DataTable();
                //dt4 = UserList.Count == 0 ? dt4 : DataHelper.ListToDataTable(((IEnumerable<dynamic>)UserList).ToList());
                //dt4.TableName = "t4";
                //tableList.Add(dt4);


                //DataTable dt5 = new DataTable();
                //dt5 = RoleList.Count == 0 ? dt5 : DataHelper.ListToDataTable(((IEnumerable<dynamic>)RoleList).ToList());
                //dt5.TableName = "t5";
                //tableList.Add(dt5);

                //DataTable dt6 = new DataTable();
                //dt6 = ModuleList.Count == 0 ? dt6 : DataHelper.ListToDataTable(((IEnumerable<dynamic>)ModuleList).ToList());
                //dt6.TableName = "t6";
                //tableList.Add(dt6);

                //DataTable dt7 = new DataTable();
                //dt7 = ModuleRelationList.Count == 0 ? dt7 : DataHelper.ListToDataTable(((IEnumerable<dynamic>)ModuleRelationList).ToList());
                //dt7.TableName = "t7";
                //tableList.Add(dt7);
                de.Add(new DictionaryEntry("Syjl", sxResult ? "通过" : "未通过"));
                //给模板对象设置数据源  
                foreach (var item in tableList)
                {
                    designer.SetDataSource(item);
                }
                foreach (var item in de)
                {
                    designer.SetDataSource(item.Key.ToString(), item.Value);
                }
                designer.Process();//全自动赋值  
                designer.Workbook.Save(saveFileName, new XlsSaveOptions(SaveFormat.Xlsx));
                designer = null;
                using (result)
                {
                    result.ExecuteAsync(JSON.Encode(Utils.ToMsg(ResultStatus.SUCCESS, "成功")));
                }
            }
            catch (Exception ex)
            {
                using (result)
                {
                    result.ExecuteAsync(JSON.Encode(Utils.ToMsg(ResultStatus.ERROR, ex.Message)));
                }
            }


        }
        public string GetSylx(string code)
        {
            switch (code)
            {
                case "1":
                    return "阶段一试验";
                case "2":
                    return "阶段二试验";
                default:
                    return "";
            }

        }
        public string GetSyxx(string code)
        {
            switch (code)
            {
                case "1":
                    return "爆炸";
                case "2":
                    return "燃烧";
                case "3":
                    return "明显变色";

                default:
                    return "无变化";

            }
        }
    }
    public class RrecordData
    {

        public string RecordTime { get; set; }
        public string TempValue { get; set; }
    }
}
